﻿#include"Date.h"

int Date::GetMOnthDay(int year, int month)
{
	assert(month > 0 && month < 13);
	int arr[13] = { 0,31,28,31,30,31,30,31,31,30,31,30,31 };
	if (month == 2 && (year % 4 == 0 && year % 100 != 0) || (year % 400) == 0)
	{
		return 29;
	}
	else
	{
		return arr[month];
	}
}
Date::Date(int year, int month, int day)
{
	if (month > 0 && month < 13 && (day > 0 && day < GetMOnthDay(year, month)))
	{
		_year = year;
		_month = month;
		_day = day;
	}
	else
	{
		cout << "日期不合法" << endl;
	}
}
bool Date::operator==(const Date& d)
{
	return _year == d._year
		&& _month == d._month
		&& _day == d._day;
}

void Date::Print()
{
	cout << _year << "/" << _month << "/" << _day << endl;
}
bool Date::operator<(const Date& d)
{
	if (_year < d._year)//年小就小
	{
		return true;
	}
	else if (_year == d._year && _month < d._month)//年相等月小就小
	{
		return true;
	}
	else if (_year == d._year && _month == d._month && _day < d._day)//年相等月相等天小就小    
	{
		return true;
	}
	else
		return false;
}

Date& Date::operator=(const Date& d)
{
	_year = d._year;
	_month = d._month;
	_day = d._day;
	return *this;
}

bool Date::operator<=(const Date& d)
{
	return *this < d || *this == d;
}

bool Date::operator>(const Date& d)
{
	return !(*this <= d);
}

bool Date::operator>=(const Date& d)
{
	return !(*this < d);
}

bool Date::operator!=(const Date& d)
{
	return !(*this == d);
}

Date& Date::operator+=(int day)
{
	if (day < 0)
	{
		*this -= -day;
		return *this;
	}
	_day += day;
	while(_day>GetMOnthDay(_year,_month))
	{
		_day -= GetMOnthDay(_year, _month);
		_month++;
		if (_month == 13)
		{
			++_year;
			_month = 1;
		}
	}
	return *this;
}

Date Date::operator+(int day)
{
	Date tmp(*this);
	tmp += day;
	return tmp;
}

Date& Date::operator++()
{
	*this += 1;
	return* this;
}

Date Date::operator++(int)
{
	Date tmp(*this);
	*this += 1;
	return tmp;
}


Date Date::operator-=(int day)
{
	_day -= day;
	while (_day <= 0)
	{
		--_month;
		if (_month == 0)
		{
			--_year;
			_month = 12;
		}
		_day += GetMOnthDay(_year, _month);
	}
	return *this;
}

Date Date::operator-(int day)
{
	Date tmp = *this;
	tmp -= day;
	return tmp;
}

Date& Date::operator--()
{
	*this -= 1;
	return*this;
}

Date Date::operator--(int)
{
	Date tmp(*this);
	*this -= 1;
	return tmp;
}


int Date::operator-(const Date& d)
{
	Date max = *this;
	Date min = d;
	int flag = 1;
	if (*this<d)
	{
		max = d;
		min = *this;
		flag = -1;
	}
	int n = 0;
	while (min != max)
	{
		++min;
		++n;
	}
	return n*flag;
}

void operator<<(ostream& out,const Date&d)
{
	out <<d._year << "年" << d._month << "月" << d._day << "日" << endl;
}


